
/**
 * extends the easyui tree with hide and show functions
 * for nodes
 */
$(document).ready(function() {
	$.extend($.fn.tree.methods,{
		hide: function(jq,target){
			return jq.each(function(){
				$(target).parent().hide();
			});
		},
		unhide: function(jq,target){
			return jq.each(function(){
				$(target).parent().show();
			});
		}
	});
});


/**
 * returns all checked nodes
 * @param 		string		treeId
 */
function getCheckedNodes(treeId){
	return $(treeId).tree('getChecked');
}


/**
 * returns the node ids of given nodes without root nodes
 * @param 		array		nodes
 * @param 		string		treeId
 * @returns 	array		nodeIds
 */
function getNodeIds(nodes, treeId){
	var nodeIds = [];	
	for(var node in nodes){
		node = nodes[node];
		if ($(treeId).tree('isLeaf', node.target))
			nodeIds.push(node.id);
	}
	return nodeIds;
}


/**
 * forms the json array in this form
 * {'producer_id': [1,2], 'category_id': [5,6,7]}
 * @param 		array		nodeIds
 */
function formJsonArr(nodeIds){
	var jsonArr = {}
	var nodeId = null;
	var idSections = null;
	var idName = null;
	var id = null;
	
	for(nodeId in nodeIds){
		nodeId = nodeIds[nodeId];
		idSections = nodeId.split('_');

		if (idSections.length >= 2){
			id = idSections[idSections.length-1];
			idName = getIdName(idSections);
			if (jsonArr[idName] == null)
				jsonArr[idName] = [];
			jsonArr[idName].push(id);
		}
	}
	return jsonArr;
}


/**
 * returns only the name of the id
 * @param 		array		idSections
 * @returns 	string		idName
 */
function getIdName(idSections){
	var idName = '';
	var count = 1;
	
	for(var i = 0; i < idSections.length-1; i++)
			idName += idSections[i] + '_';
			
	idName = idName.substring(0, idName.length-1); 		//remove the last '_';
	return idName;
}


/**
 * returns json encoded node id infos
 * @param 		string		treeId
 */
function getCheckedJsonInfo(treeId){
	treeId = getJqueryId(treeId);
	return $.toJSON(formJsonArr(getNodeIds(getCheckedNodes(treeId), treeId)));
}